package com.dongbing.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class NettyServer {
    public static void main(String[] args) throws IOException {
        // 信道集合
        List<SocketChannel> channelList = new ArrayList<>();
        // 1. 创建 ServerSocketChannel
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        // 2. 设置服务端监听端口 --> client通过网络进行访问 ip:localhost http://localhost:8989
        socketChannel.bind(new InetSocketAddress(8989));
        // 创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(20);
        // 3. 接受client请求
        for (;;) {

            System.out.println("等待连接服务器");

            SocketChannel accept = socketChannel.accept();

            System.out.println("服务器已连接");

            channelList.add(accept);

            for (SocketChannel channel : channelList) {

                System.out.println("开始实际的数据通讯");

                channel.read(buffer);

                buffer.flip();

                CharBuffer decode = StandardCharsets.UTF_8.decode(buffer);

                System.out.println("decode = " + decode);

                buffer.clear();

                System.out.println("通信已经结束");
            }

        }
    }
}
